package com.face.receive.jsu;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.catalina.User;
import org.apache.naming.java.javaURLContextFactory;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.json.JSONException;
import org.json.JSONObject;

import com.face.bean.jsu.FindPopulation;
import com.face.bean.jsu.LostPopulationMessage;
import com.face.common.jsu.FindFaceSetOutid;
import com.face.common.jsu.LostFaceSetOutid;
import com.face.common.jsu.Rename;
import com.face.operate.jsu.FindToken_Operate;
import com.face.operate.jsu.LostMessage;
import com.face.operate.jsu.Face_Operate;
import com.face.operate.jsu.LostToken_Operate;
import com.face.photo.jsu.photo;
import com.face.push.jsu.Push;

import io.yunba.java.manager.YunBaManager;

@WebServlet("/Rexinren")
public class ReceiveFind extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private ServletFileUpload upload;
	private final long MAXSize = 4194304 * 2L;// 4*2MB
	
	// 热心人士提供照片合集id
	LostFaceSetOutid lostFaceSetOutid = LostFaceSetOutid.getInstance(); 
	String faceset_outid1 = lostFaceSetOutid.getLostFaceSetID();
	// 走失人口家属提供照片合集id
	FindFaceSetOutid findFaceSetOutid = FindFaceSetOutid.getInstance();
	String faceset_outid2 = findFaceSetOutid.getFindFaceSetID();
	
	String lostUrl = "http://47.106.35.203:8080/lost/";
	String findUrl = "http://47.106.35.203:8080/find/";
	String saveDir = "/root/find/";
	
	public void init(ServletConfig config) throws ServletException {
		FileItemFactory factory = new DiskFileItemFactory();
		this.upload = new ServletFileUpload(factory);
		this.upload.setSizeMax(this.MAXSize);
		this.upload.setHeaderEncoding("UTF-8");
	  
	}

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String filename = "";
		String filepath = "";
		JSONObject json = new JSONObject();
		JSONObject js = new JSONObject();
		JSONArray array = new JSONArray();
		Map<String, String> map = new HashMap<>();
		LostToken_Operate tok = new LostToken_Operate();
        LostMessage lostMessage = new LostMessage();
        List<LostPopulationMessage> messages = null;
        JSONArray jsa = new JSONArray();
        
		try {
			List<FileItem> items = this.upload.parseRequest(new ServletRequestContext(request));
			if (items != null && !items.isEmpty()) {
				for (FileItem fileItem : items) {
					if (fileItem.isFormField()) {
						String inputName = fileItem.getFieldName();
						String inputValue = new String(fileItem.getString("UTF-8"));
						map.put(inputName, inputValue);
						System.out.println(inputName + ":" + inputValue);
					} else {
						filename = Rename.rename();
						filepath = saveDir+ filename;
						System.out.println("文件保存路径为:" + filepath);
						File file = new File(filepath);
						InputStream inputSteam = fileItem.getInputStream();
						BufferedInputStream fis = new BufferedInputStream(inputSteam);
						FileOutputStream fos = new FileOutputStream(file);
						int f;
						while ((f = fis.read()) != -1) {
							fos.write(f);
						}
						fos.flush();
						fos.close();
						fis.close();
						inputSteam.close();
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
			System.out.println("上传失败");
		}

		Face_Operate face = new Face_Operate();
		System.out.println("文件：" + filename + "上传成功!");
		byte[] fb = face.toByteArray(filepath);
		// 提取人脸信息，返回识别码
		String facetoken = face.toFaceToken(fb);
		System.out.println("提取到的人脸信息：" + facetoken);
		try {
			if (facetoken.equals("failed")) {
				json.put("message", "invalid");
				File file = new File(filepath);
				if (file.exists() && file.isFile()) {
				file.delete();
				}
			} else {
				json.put("message", "ok");
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Timestamp timestamp = Timestamp.valueOf(dateFormat.format(new Date()));
				js.put("url", findUrl + filename);
				js.put("location", map.get("location"));
				js.put("time", dateFormat.format(timestamp));
				js.put("message",map.get("message"));
				String address = map.get("location");
				net.sf.json.JSONObject jsonobject = net.sf.json.JSONObject.fromObject(address);
				String location = new String();
				String province = new String();
				String city = null;
				
				if (address.contains("Province")) {
					province = jsonobject.getString("Province");
				}
				if (address.contains("City")) {
					city = jsonobject.getString("City");
				}
				if (address.contains("District")) {
					String district = jsonobject.getString("District");
					location = location + district;
				}
				if (address.contains("Street")) {
					String street = jsonobject.getString("Street");
					location = location + street;
				}
				if (address.contains("Number")) {
					String number = jsonobject.getString("Number");
					location = location + number;
				}
				if (address.contains("POIName")) {
					String POIName = jsonobject.getString("POIName");
					location = location + POIName;
				}
				if (address.contains("AOIName")) {
					String AOIName = jsonobject.getString("AOIName");
					location = location + AOIName;
				}
				
				FindToken_Operate tok2 = new FindToken_Operate();
				tok2.Save(facetoken, filename, province,city,location, timestamp,map.get("message"));
				// 将人脸标识放入容器
				face.add_faceset(facetoken, faceset_outid1);
				
				List<String> faceList = face.search_faceset(fb, facetoken, faceset_outid2);
				if(faceList.size()!=0){
					IdentityHashMap<String, String> usernames = tok.selectUsernameByFaceid(faceList);
					if(!usernames.isEmpty()){
						messages = lostMessage.selectByUsernameAndName(usernames);
					}
				}
				
				if(messages!=null){
				for(int i=0;i<messages.size();i++){
						LostPopulationMessage message = messages.get(i);
						net.sf.json.JSONObject jsb = net.sf.json.JSONObject.fromObject(message);
						String username = message.getUsername();
						String name = message.getName();
						List<String> paths = tok.selectPathByUserNameAndName(username,name);
						JSONArray jsonArray = new JSONArray();
						for(String s:paths){
							jsonArray.add(lostUrl+s);
						}
						System.out.println(jsonArray.toString());
						jsb.put("url", jsonArray);
						array.add(jsb);
						//推送消息
						Push.push(username, js.toString());
				}
				}
					
					json.put("notice", array);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
		response.setContentType("application/json; charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write(json.toString());
		System.out.println("返回的json数据：" + json.toString());
	}
}
